package com.yhsoft.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yhsoft.common.response.Option;
import com.yhsoft.common.vo.Result;
import com.yhsoft.sys.controller.request.AddRoleInVo;
import com.yhsoft.sys.entity.Role;
import com.yhsoft.sys.entity.User;
import com.yhsoft.sys.entity.UserRole;
import com.yhsoft.sys.mapper.UserRoleMapper;
import com.yhsoft.sys.service.IRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author yyyyyyyh
 * @since 2023-08-30
 */
@RestController
@Api(tags = {"A-角色接口列表"})
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private IRoleService roleService;

    @Resource
    private UserRoleMapper userRoleMapper;

    @ApiOperation("分页查询角色列表")
    @GetMapping("/getRoleList")
    public Result<Map<String, Object>> getRoleList(@RequestParam(value = "roleName", required = false) String roleName,
                                                   @RequestParam(value = "pageNo") Long pageNo,
                                                   @RequestParam(value = "pageSize") Long pageSize) {
        // 根据token获取用户信息
        User userinfo = roleService.getUserInfoByToken();
        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasLength(roleName), Role::getRoleName, roleName)
                .eq(Role::getCompanyId, userinfo.getCompanyId());
        wrapper.orderByDesc(Role::getRoleId);

        Page<Role> page = new Page<>(pageNo, pageSize);
        roleService.page(page, wrapper);

        Map<String, Object> data = new HashMap<>();
        data.put("total", page.getTotal());
        data.put("rows", page.getRecords());

        return Result.success(data);

    }

    @ApiOperation("新增角色")
    @PostMapping("/addRole")
    public Result<?> addRole(@RequestBody AddRoleInVo inVo) {
        if (!StringUtils.hasLength(inVo.getRoleName())) {
            return Result.fail("新增角色失败，请输入角色名称！");
        }
        User userinfo = roleService.getUserInfoByToken();
        Role role = new Role();
        role.setRoleName(inVo.getRoleName());
        role.setRoleDesc(inVo.getRoleDesc());
        role.setDeleted(0);
        role.setCompanyId(userinfo.getCompanyId());
        roleService.addRole(role);
        return Result.success("新增角色成功");
    }

    @ApiOperation("修改角色")
    @PutMapping("/updateRole")
    public Result<?> updateRole(@RequestBody Role role) {
        roleService.updateRole(role);
        return Result.success("修改角色成功");
    }

    @ApiOperation("根据角色ID获取角色")
    @GetMapping("/getRoleById/{id}")
    public Result<Role> getRoleById(@PathVariable("id") Integer id) {
        Role role = roleService.getRoleById(id);
        return Result.success(role);
    }

    @ApiOperation("根据ID删除角色")
    @DeleteMapping("/deleteRoleById/{id}")
    public Result<?> deleteRoleById(@PathVariable("id") Integer id) {
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRole::getRoleId, id);
        List<UserRole> UserRole = userRoleMapper.selectList(wrapper);
        if (UserRole.size() > 0) {
            return Result.fail("有" + UserRole.size() + "个用户关联了该角色，无法删除！");
        }
        roleService.deleteRoleById(id);
        return Result.success("删除角色成功");
    }

    @ApiOperation("获取全部角色")
    @GetMapping("/getAllRole")
    public Result<List<Option>> getAllRole() {
        // 根据token获取用户信息
        User userinfo = roleService.getUserInfoByToken();
        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Role::getCompanyId, userinfo.getCompanyId());
        List<Role> roleList = roleService.list(wrapper);
        List<Option> options = roleList.stream().map(r -> {
            Option option = new Option(r.getRoleId().toString(), r.getRoleName());
            return option;
        }).collect(Collectors.toList());
        return Result.success(options);
    }

}
